layui.use(['form','tree','element','laydate','table','laytpl','layer','jquery'],function(){
    var form = layui.form,
        element = layui.element;
    $ = layui.$;
    var layer = parent.layer === undefined ? layui.layer : top.layer;
    var table = layui.table;
    var laytpl = layui.laytpl;
    var layedit = layui.layedit;
    var laydate = layui.laydate;

    //场景数据
    var treeData = {
        elem: '#tree' //指定元素
        , target: '_blank' //是否新选项卡打开（比如节点返回href才有效）
        , click: function (item) { //点击节点回调
            //查询当前场景下的设备
            $.get("/equipment/query?sceneId=" + item.id,function (data) {
                //刷新右侧设备列表和检测项目列表
                $.get("/equipment/query?sceneId=" + item.id,function (data) {
                    $("#equipment-list").html('');
                    $("#equipment-list").append('<option value="">请选择设备</option>');
                    $.each(data.data,function (i,ele) {
                        $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
                    });
                    form.render('select');
                });
            });
        },
        nodes:null
    };
    //异步加载设备所处场景数据
    $.get('/scene/tree',function(data) {
        if (data.data.length != 0) {
            data.data[0].spread = true;
            var children = data.data[0].children;
            if (children != null && children.length != 0) {
                $.each(children,function (i, ele) {
                    ele.spread = true;
                });
            }
        }
        treeData.nodes = data.data;
        layui.tree(treeData);
        $("#tree-scenery").hide();
    });

    //采集设备数据
    $.get("/equipment/list",function (data) {
        /*$("#equipment-list").append('<option value="">请选择</option>');*/
        $.each(data.data,function (i,ele) {
            $("#equipment-list").append('<option value="'+ ele.id +'">'+ ele.name +'</option>');
        });
        form.render('select');
        //刷新设备对应的数据采集项
        form.on('select(equipment-list)',function (data) {
            $.get("/equipment/channel/query?equipmentId=" + data.value,function (data) {
                $("#checkItem").html("");
                $("#checkItem").append('<option value="">请选择</option>');
                $.each(data.data,function (i,ele) {
                    $("#checkItem").append('<option value="'+ ele.collectChannelApplicateTypeId +'">'+ ele.channelName +'</option>');
                });
                form.render('select');
            });
        });
    });

    //搜索设备信息
    laydate.render({
        elem: '#downAcquisitionTime'
    });
    laydate.render({
        elem: '#upAcquisitionTime'
    });
    $(".search_btn").on("click",function(){
        var equipmentId = $("#equipment-list").val();
        var checkItemId = $("#checkItem").val();
        var model = $("#model").val();
        var upAcquisitionTime = $("#upAcquisitionTime").val();
        var downAcquisitionTime = $("#downAcquisitionTime").val();
        var searchObj = {};
        if(equipmentId == ''){
            layer.msg("请选择搜索设备");
            return;
        }
        if(checkItemId == ''){
            layer.msg("请选择搜索预测项目");
            return;
        }
        if (upAcquisitionTime != null && upAcquisitionTime != "") {
            searchObj.upAcquisitionTime = upAcquisitionTime + "T00:00:00Z";
        }
        if (downAcquisitionTime != null && downAcquisitionTime != "") {
            searchObj.downAcquisitionTime = downAcquisitionTime + "T00:00:00Z";
        }
        searchObj.equipmentId = equipmentId;
        searchObj.checkItemId = checkItemId;

        //测试
        searchObj.page = 0;
        searchObj.limit = 1000;
        $("#loading").show();
        $("#tip").hide();

        //判断测试模型
        if (model == 'ARIMA') {
            $.get('/datarecord/forecast/arima',searchObj,function (data) {

                if (data.data.orgindata.length <= 0) {
                    //关闭加载动画
                    $("#loading").hide();
                    layer.msg("没有找到数据！换一个时间范围试试？");
                    return;
                }
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                var curtime = null;//最新的上报时间
                var curdata = '-';
                var xAxisPredictdataArr = [];
                var seriesPredictArr = [];
                $.each(data.data.orgindata,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    if (j === 0) {
                        curtime = ele.acquisitionTime;
                        curdata = ele.processedData;
                    }
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;

                    //预测
                    seriesPredictArr.unshift('-');
                });
                //添加数据衔接点
                var date = new Date(curtime);
                curtime = date.getTime();
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                xAxisdataArr.push(dateStr);
                seriesPredictArr.push(curdata);

                /*$.each(data.data.predictdata,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesPredictArr.push(ele);
                });*/

                var predictData = data.data.predictdata;
                //查找当前道预警值
                var warning = null;
                $.ajax({
                    url:'/warning/config/equipment/list?sceneId=' + data.data.orgindata[0].sceneId + '&checkItemId=' + data.data.orgindata[0].checkItemId,
                    type: 'get',
                    async: false,
                    success: function (data) {
                        if (data.data.length != 0) {
                            warning = data.data[0];
                        }
                    }
                });
                for (var i = 0;i < predictData.length - 50;i++) {
                    var date = new Date(curtime + 20*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesPredictArr.push(predictData[i]);
                    // console.log(parseFloat(predictData[i]));
                    // console.log(warning.maxValue);
                    // console.log(warning.maxValue < parseFloat(predictData[i]));
                    if (warning != null && parseFloat(predictData[i]) >= warning.maxValue) {
                        console.log($("#tips"));
                        $("#tips").show();
                    }
                }

                //对预测出来的结果进行降噪处理
                /*if (seriesPredictArr.length >= 3) {
                    for (var i = 0;i < seriesPredictArr.length - 1;i++) {
                        if (seriesPredictArr[i] - seriesPredictArr[i + 1])
                    }
                }*/

                //初始化统计图
                initChart(0,xAxisdataArr,seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr);
            });
        } else if(model == 'LSTM-RNN'){
            searchObj.limit = 350;
            $.get('/datarecord/forecast/lstmrnn',searchObj,function (data) {
                console.log(data);
                if (data.data.orgindata.length <= 0) {
                    //关闭加载动画
                    $("#loading").hide();
                    layer.msg("没有找到数据！换一个时间范围试试？");
                    return;
                }
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                var curtime = null;//最新的上报时间
                var curdata = '-';
                var xAxisPredictdataArr = [];   //历史数据
                var seriesPredictArr = [];  //预测数据
                var seriesTestPredictArr = [];  //测试数据
                var seriesRealPredictArr = [];  //真实测试数据
                $.each(data.data.orgindata,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    if (j === 0) {
                        curtime = ele.acquisitionTime;
                        curdata = ele.processedData;
                    }
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;

                    //预测
                    seriesPredictArr.unshift('-');
                    /*seriesTestPredictArr.unshift('-');*/
                    seriesRealPredictArr.unshift('-');
                });
                //添加数据衔接点
                var date = new Date(curtime);
                curtime = date.getTime();
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                xAxisdataArr.push(dateStr);
                seriesPredictArr.push(curdata);
                seriesTestPredictArr.unshift(curdata);

                //拟合测试数据的预测数据
                $.each(data.data.predictdata,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesPredictArr.push(ele);

                    seriesArr.push(ele);
                    seriesRealPredictArr.unshift('-');
                });

                //测试是预测曲线是否拟合数据
                /*var testdataArr = data.data.testdata;
                for (var i = testdataArr.length - 1;i >= 0;i--) {
                    seriesTestPredictArr.push(testdataArr[i].processedData);
                }*/

                //真实的预测数据
                $.each(data.data.realPredictData,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesRealPredictArr.push(ele);
                });

                //初始化统计图
                initChart2(0,xAxisdataArr,seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr,seriesTestPredictArr,seriesRealPredictArr);
            });
        } else if(model == 'RandomForest') {
            searchObj.limit = 350;
            $.get('/datarecord/forecast/lstmrnn',searchObj,function (data) {
                console.log(data);
                if (data.data.orgindata.length <= 0) {
                    //关闭加载动画
                    $("#loading").hide();
                    layer.msg("没有找到数据！换一个时间范围试试？");
                    return;
                }
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                var curtime = null;//最新的上报时间
                var curdata = '-';
                var xAxisPredictdataArr = [];   //历史数据
                var seriesPredictArr = [];  //预测数据
                var seriesTestPredictArr = [];  //测试数据
                var seriesRealPredictArr = [];  //真实测试数据
                $.each(data.data.orgindata,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    if (j === 0) {
                        curtime = ele.acquisitionTime;
                        curdata = ele.processedData;
                    }
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;

                    //预测
                    seriesPredictArr.unshift('-');
                    /*seriesTestPredictArr.unshift('-');*/
                    seriesRealPredictArr.unshift('-');
                });
                //添加数据衔接点
                var date = new Date(curtime);
                curtime = date.getTime();
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                xAxisdataArr.push(dateStr);
                seriesPredictArr.push(curdata);
                seriesTestPredictArr.unshift(curdata);

                //拟合测试数据的预测数据
                $.each(data.data.predictdata,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesPredictArr.push(ele);

                    seriesArr.push(ele);
                    seriesRealPredictArr.unshift('-');
                });

                //测试是预测曲线是否拟合数据
                /*var testdataArr = data.data.testdata;
                for (var i = testdataArr.length - 1;i >= 0;i--) {
                    seriesTestPredictArr.push(testdataArr[i].processedData);
                }*/

                //真实的预测数据
                $.each(data.data.realPredictData,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesRealPredictArr.push(ele);
                });

                //初始化统计图
                initChart2(0,xAxisdataArr,seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr,seriesTestPredictArr,seriesRealPredictArr);
            });
        } else if (model == "SVM") {
            searchObj.limit = 350;
            $.get('/datarecord/forecast/lstmrnn',searchObj,function (data) {
                console.log(data);
                if (data.data.orgindata.length <= 0) {
                    //关闭加载动画
                    $("#loading").hide();
                    layer.msg("没有找到数据！换一个时间范围试试？");
                    return;
                }
                //x轴时间组件
                var xAxisdataArr = [];
                var seriesArr = [];
                var checkMessage = {};
                var curtime = null;//最新的上报时间
                var curdata = '-';
                var xAxisPredictdataArr = [];   //历史数据
                var seriesPredictArr = [];  //预测数据
                var seriesTestPredictArr = [];  //测试数据
                var seriesRealPredictArr = [];  //真实测试数据
                $.each(data.data.orgindata,function (j, ele) {
                    var date = new Date(ele.acquisitionTime);
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    if (j === 0) {
                        curtime = ele.acquisitionTime;
                        curdata = ele.processedData;
                    }
                    xAxisdataArr.unshift(dateStr);
                    seriesArr.unshift(ele.processedData);
                    checkMessage.title = ele.checkItemName + "趋势";
                    checkMessage.legendData = ele.checkItemName;
                    checkMessage.seriesName = ele.checkItemName;
                    checkMessage.yAxisformatter = ele.unit;

                    //预测
                    /*seriesPredictArr.unshift(ele.processedData);*/
                    seriesTestPredictArr.unshift('-');
                    seriesRealPredictArr.unshift('-');
                });
                //添加数据衔接点
                var date = new Date(curtime);
                curtime = date.getTime();
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                xAxisdataArr.push(dateStr);
                seriesPredictArr.push(curdata);
                seriesTestPredictArr.unshift(curdata);

                //拟合测试数据的预测数据
                $.each(data.data.predictdata,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesPredictArr.push(ele);

                    seriesArr.push(ele);
                    seriesRealPredictArr.unshift('-');
                });

                //测试是预测曲线是否拟合数据
                /*var testdataArr = data.data.testdata;
                for (var i = testdataArr.length - 1;i >= 0;i--) {
                    seriesTestPredictArr.push(testdataArr[i].processedData);
                }*/

                //真实的预测数据
                $.each(data.data.realPredictData,function (j, ele) {
                    var date = new Date(curtime + 5*60*1000);
                    curtime = date.getTime();
                    var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                    xAxisdataArr.push(dateStr);
                    seriesRealPredictArr.push(ele);
                });

                //初始化统计图
                initChart2(0,xAxisdataArr,seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr,seriesTestPredictArr,seriesRealPredictArr);
            });
        }


        /*$.get('/datarecord/forecast/arima',{equipmentId:searchObj.equipmentId,checkItemId:searchObj.checkItemId,page:searchObj.page,limit:searchObj.limit},function (data) {
            console.log(data);
            if (data.data.orgindata.length <= 0) {
                //关闭加载动画
                $("#loading").hide();
                layer.msg("没有找到数据！换一个时间范围试试？");
                return;
            }
            //x轴时间组件
            var xAxisdataArr = [];
            var seriesArr = [];
            var checkMessage = {};
            var curtime = null;//最新的上报时间
            var curdata = '-';
            var xAxisPredictdataArr = [];
            var seriesPredictArr = [];
            $.each(data.data.orgindata,function (j, ele) {
                var date = new Date(ele.acquisitionTime);
                var dateStr = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + date.getDate() + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
                if (j === 0) {
                    curtime = ele.acquisitionTime;
                    curdata = ele.processedData;
                }
                xAxisdataArr.unshift(dateStr);
                seriesArr.unshift(ele.processedData);
                checkMessage.title = ele.checkItemName + "趋势";
                checkMessage.legendData = ele.checkItemName;
                checkMessage.seriesName = ele.checkItemName;
                checkMessage.yAxisformatter = ele.unit;
            });

            //初始化统计图
            initChart(1,xAxisdataArr,seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr);
        });
*/
    });

    /**
     * 初始化统计图
     * @param index
     * @param xAxisdataArr
     * @param seriesArr
     * @param checkMessage
     * @param xAxisPredictdataArr
     * @param seriesPredictArr  预测后的数据
     */
    function initChart(index,xAxisdataArr, seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr) {
        $("#loading").hide();
        $("#loading").next().remove();
        //关闭加载动画
        var innerHtml = '<div class="layui-elem-quote layui-quote-nm magb0 echart-box" style="border-left: 5px solid #e6e6e6;">' +
            '                <div id="line-chart-'+ index +'" style="margin-top:10px;width: 95%; height: 400px;">' +
            '                </div>' +
            '            </div>';
        $("#echart-content").append(innerHtml);
        //折线图
        var lineChart = echarts.init(document.getElementById('line-chart-' + index));
        var option = {
            title: {
                text: checkMessage.title,
                subtext: ' '
            },
            tooltip: {
                trigger: 'axis'
            },

            legend: {
                data:['真实值','预测值','原始值']
            },
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: {readOnly: false},
                    magicType: {type: ['line', 'bar']},
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                data: xAxisdataArr
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} ' + checkMessage.yAxisformatter
                }
            },
            color: ['#0e94eb', '#FF5722','#448822'],
            series: [
                {
                    name:'真实值',
                    type:'line',
                    data:seriesArr,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    },
                    markLine: {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    },
                    lineStyle:{
                        normal: {
                            color:"#0e94eb"
                        }
                    }
                },{
                    name:'预测值',
                    type:'line',
                    data:seriesPredictArr,
                    lineStyle:{
                        normal: {
                            color:"#FF5722"
                        }
                    }
                }
            ]
        };
        lineChart.setOption(option);
    }

    /**
     * 初始化统计图
     * @param index
     * @param xAxisdataArr
     * @param seriesArr
     * @param checkMessage
     * @param xAxisPredictdataArr
     * @param seriesPredictArr  预测后的数据
     */
    function initChart2(index,xAxisdataArr, seriesArr,checkMessage,xAxisPredictdataArr,seriesPredictArr,seriesTestPredictArr,seriesRealPredictArr) {
        $("#loading").hide();
        $("#loading").next().remove();
        //关闭加载动画
        var innerHtml = '<div class="layui-elem-quote layui-quote-nm magb0 echart-box" style="border-left: 5px solid #e6e6e6;">' +
            '                <div id="line-chart-'+ index +'" style="margin-top:10px;width: 95%; height: 400px;">' +
            '                </div>' +
            '            </div>';
        $("#echart-content").append(innerHtml);
        //折线图
        var lineChart = echarts.init(document.getElementById('line-chart-' + index));
        var option = {
            title: {
                text: checkMessage.title,
                subtext: ' '
            },
            tooltip: {
                trigger: 'axis'
            },

            legend: {
                data:['真实值','拟合值','测试值','预测值']
            },
            toolbox: {
                show: true,
                feature: {
                    dataZoom: {
                        yAxisIndex: 'none'
                    },
                    dataView: {readOnly: false},
                    magicType: {type: ['line', 'bar']},
                    restore: {},
                    saveAsImage: {}
                }
            },
            xAxis:  {
                type: 'category',
                boundaryGap: false,
                data: xAxisdataArr
            },
            yAxis: {
                type: 'value',
                axisLabel: {
                    formatter: '{value} ' + checkMessage.yAxisformatter
                }
            },
            color: ['#0e94eb', '#FF5722','#448822','#15e4dd'],
            series: [
                {
                    name:'真实值',
                    type:'line',
                    data:seriesArr,
                    markPoint: {
                        data: [
                            {type: 'max', name: '最大值'},
                            {type: 'min', name: '最小值'}
                        ]
                    },
                    markLine: {
                        data: [
                            {type: 'average', name: '平均值'}
                        ]
                    },
                    lineStyle:{
                        normal: {
                            color:"#0e94eb"
                        }
                    }
                },{
                    name:'拟合值',
                    type:'line',
                    data:seriesPredictArr,
                    lineStyle:{
                        normal: {
                            color:"#FF5722",
                            type:'dotted',  //'dotted'虚线 'solid'实线
                            width:4
                        }
                    }
                }/*,{
                    name:'测试值',
                    type:'line',
                    data:seriesTestPredictArr,
                    lineStyle:{
                        normal: {
                            color:"#448822"
                        }
                    }
                }*/,{
                    name:'预测值',
                    type:'line',
                    data:seriesRealPredictArr,
                    lineStyle:{
                        normal: {
                            color:"#15e4dd"
                        }
                    }
                }
            ]
        };
        lineChart.setOption(option);
    }


});